package com.zjut.zs.school.dao;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.zjut.an.util.module.PageModule;
import com.zjut.zs.userinfo.dao.ZsUserinfo;

/**
 * A data access object (DAO) providing persistence and search support for
 * ZsSchool entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.zjut.zs.school.dao.ZsSchool
 * @author MyEclipse Persistence Tools
 */

public class ZsSchoolDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory
			.getLogger(ZsSchoolDAO.class);
	// property constants
	public static final String SC_ID = "scId";
	public static final String SC_CODE = "scCode";
	public static final String SC_NAME = "scName";
	public static final String SC_ENNAME = "scEnname";
	public static final String SC_SITE = "scSite";
	public static final String SC_COPYRIGHT = "scCopyright";
	public static final String SC_ACTIVE = "scActive";
	public static final String SC_PASSWORD = "scPassword";
	public static final String SC_SUB_JS = "scSubJs";
	public static final String APP_PAGE = "appPage";
	public static final String SC_REG_ACTIVE = "scRegActive";
	public static final String SC_APP_ACTIVE = "scAppActive";
	public static final String SC_PAY_ACTIVE = "scPayActive";
	public static final String SC_PRINT_ACTIVE = "scPrintActive";
	public static final String SC_SEARCH_ACTIVE = "scSearchActive";
	public static final String SC_CHECKPUB_ACTIVE = "scCheckpubActive";
	public static final String SC_PASSPUB_ACTIVE = "scPasspubActive";
	public static final String SC_TESTPUB_ACTIVE = "scTestpubActive";

	protected void initDao() {
		// do nothing
	}

	public void sort(Criteria criteria, String sort, String order) {
		if (sort!=null && order!=null) {
			if (order.equals("asc")) {
				criteria.addOrder(Order.asc(sort));
			} else {
				criteria.addOrder(Order.desc(sort));
			}
		} else {
			criteria.addOrder(Order.desc(SC_ID));			
		}
	}
	
	public void save(ZsSchool transientInstance) {
		log.debug("saving ZsSchool instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void update(ZsSchool transientInstance) {
		log.debug("updating ZsSchool instance");
		try {
			getHibernateTemplate().update(transientInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}
	
	public void delete(ZsSchool persistentInstance) {
		log.debug("deleting ZsSchool instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public ZsSchool findById(java.lang.Integer id) {
		log.debug("getting ZsSchool instance with id: " + id);
		try {
			ZsSchool instance = (ZsSchool) getHibernateTemplate().get(
					"com.zjut.zs.school.dao.ZsSchool", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(ZsSchool instance) {
		log.debug("finding ZsSchool instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding ZsSchool instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from ZsSchool as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByScCode(Object scCode) {
		return findByProperty(SC_CODE, scCode);
	}

	public List findByScName(Object scName) {
		return findByProperty(SC_NAME, scName);
	}

	public List findByScEnname(Object scEnname) {
		return findByProperty(SC_ENNAME, scEnname);
	}

	public List findByScSite(Object scSite) {
		return findByProperty(SC_SITE, scSite);
	}

	public List findByScCopyright(Object scCopyright) {
		return findByProperty(SC_COPYRIGHT, scCopyright);
	}

	public List findByScActive(Object scActive) {
		return findByProperty(SC_ACTIVE, scActive);
	}

	public List findByScPassword(Object scPassword) {
		return findByProperty(SC_PASSWORD, scPassword);
	}

	public List findByScSubJs(Object scSubJs) {
		return findByProperty(SC_SUB_JS, scSubJs);
	}

	public List findByAppPage(Object appPage) {
		return findByProperty(APP_PAGE, appPage);
	}

	public List findByScRegActive(Object scRegActive) {
		return findByProperty(SC_REG_ACTIVE, scRegActive);
	}

	public List findByScAppActive(Object scAppActive) {
		return findByProperty(SC_APP_ACTIVE, scAppActive);
	}

	public List findByScPayActive(Object scPayActive) {
		return findByProperty(SC_PAY_ACTIVE, scPayActive);
	}

	public List findByScPrintActive(Object scPrintActive) {
		return findByProperty(SC_PRINT_ACTIVE, scPrintActive);
	}

	public List findByScSearchActive(Object scSearchActive) {
		return findByProperty(SC_SEARCH_ACTIVE, scSearchActive);
	}

	public List findAll() {
		log.debug("finding all ZsSchool instances");
		try {
			String queryString = "from ZsSchool";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public ZsSchool merge(ZsSchool detachedInstance) {
		log.debug("merging ZsSchool instance");
		try {
			ZsSchool result = (ZsSchool) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(ZsSchool instance) {
		log.debug("attaching dirty ZsSchool instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(ZsSchool instance) {
		log.debug("attaching clean ZsSchool instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static ZsSchoolDAO getFromApplicationContext(ApplicationContext ctx) {
		return (ZsSchoolDAO) ctx.getBean("ZsSchoolDAO");
	}

	@SuppressWarnings("unchecked")
	public PageModule findByInstance(final int pageNumber ,final int pageSize, String sort, String order, final ZsSchool obj){
		try {
			int startIndex = (pageNumber - 1) * pageSize;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			List list;
			Criteria criteria = session.createCriteria(ZsSchool.class);
			
			if (!isEmpty(obj.getScCode())) {
				criteria.add(Restrictions.eq(SC_CODE, obj.getScCode()));
			}
			if (!isEmpty(obj.getScName())) {
				criteria.add(Restrictions.like(SC_NAME, obj.getScName(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getScEnname())) {
				criteria.add(Restrictions.like(SC_ENNAME, obj.getScEnname(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getScSite())) {
				criteria.add(Restrictions.like(SC_SITE, obj.getScSite(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getScCopyright())) {
				criteria.add(Restrictions.like(SC_COPYRIGHT, obj.getScCopyright(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getScActive())) {
				criteria.add(Restrictions.eq(SC_ACTIVE, obj.getScActive()));
			}
			if (!isEmpty(obj.getScPassword())) {
				criteria.add(Restrictions.eq(SC_PASSWORD, obj.getScPassword()));
			}
			if (!isEmpty(obj.getScRegActive())) {
				criteria.add(Restrictions.eq(SC_REG_ACTIVE, obj.getScRegActive()));
			}
			if (!isEmpty(obj.getScAppActive())) {
				criteria.add(Restrictions.eq(SC_APP_ACTIVE, obj.getScAppActive()));
			}
			if (!isEmpty(obj.getScPayActive())) {
				criteria.add(Restrictions.eq(SC_PAY_ACTIVE, obj.getScPayActive()));
			}
			if (!isEmpty(obj.getScPrintActive())) {
				criteria.add(Restrictions.eq(SC_PRINT_ACTIVE, obj.getScPrintActive()));
			}
			if (!isEmpty(obj.getScSearchActive())) {
				criteria.add(Restrictions.eq(SC_SEARCH_ACTIVE, obj.getScSearchActive()));
			}
			if (!isEmpty(obj.getScCheckpubActive())) {
				criteria.add(Restrictions.eq(SC_CHECKPUB_ACTIVE, obj.getScCheckpubActive()));
			}
			if (!isEmpty(obj.getScPasspubActive())) {
				criteria.add(Restrictions.eq(SC_PASSPUB_ACTIVE, obj.getScPasspubActive()));
			}
			if (!isEmpty(obj.getScTestpubActive())) {
				criteria.add(Restrictions.eq(SC_TESTPUB_ACTIVE, obj.getScTestpubActive()));
			}
			//补充
			
			this.sort(criteria, sort, order);
			
			criteria.setFirstResult(startIndex);
			criteria.setMaxResults(pageSize);
			list = criteria.list();
			session.close();
			return new PageModule(pageNumber, pageSize, countByInstance(obj), list);
		} catch (RuntimeException re) {
			log.error("findByInstance failed", re);
			throw re;
		}
	}
	
	public int countByInstance(final ZsSchool obj) {
		log.debug("finding the number of ZsSchool instance");
		try {
			int count = 0;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Criteria criteria = session.createCriteria(ZsSchool.class);
			
			if (!isEmpty(obj.getScCode())) {
				criteria.add(Restrictions.eq(SC_CODE, obj.getScCode()));
			}
			if (!isEmpty(obj.getScName())) {
				criteria.add(Restrictions.like(SC_NAME, obj.getScName(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getScEnname())) {
				criteria.add(Restrictions.like(SC_ENNAME, obj.getScEnname(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getScSite())) {
				criteria.add(Restrictions.like(SC_SITE, obj.getScSite(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getScCopyright())) {
				criteria.add(Restrictions.like(SC_COPYRIGHT, obj.getScCopyright(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getScActive())) {
				criteria.add(Restrictions.eq(SC_ACTIVE, obj.getScActive()));
			}
			if (!isEmpty(obj.getScPassword())) {
				criteria.add(Restrictions.eq(SC_PASSWORD, obj.getScPassword()));
			}
			if (!isEmpty(obj.getScRegActive())) {
				criteria.add(Restrictions.eq(SC_REG_ACTIVE, obj.getScRegActive()));
			}
			if (!isEmpty(obj.getScAppActive())) {
				criteria.add(Restrictions.eq(SC_APP_ACTIVE, obj.getScAppActive()));
			}
			if (!isEmpty(obj.getScPayActive())) {
				criteria.add(Restrictions.eq(SC_PAY_ACTIVE, obj.getScPayActive()));
			}
			if (!isEmpty(obj.getScPrintActive())) {
				criteria.add(Restrictions.eq(SC_PRINT_ACTIVE, obj.getScPrintActive()));
			}
			if (!isEmpty(obj.getScSearchActive())) {
				criteria.add(Restrictions.eq(SC_SEARCH_ACTIVE, obj.getScSearchActive()));
			}
			if (!isEmpty(obj.getScCheckpubActive())) {
				criteria.add(Restrictions.eq(SC_CHECKPUB_ACTIVE, obj.getScCheckpubActive()));
			}
			if (!isEmpty(obj.getScPasspubActive())) {
				criteria.add(Restrictions.eq(SC_PASSPUB_ACTIVE, obj.getScPasspubActive()));
			}
			if (!isEmpty(obj.getScTestpubActive())) {
				criteria.add(Restrictions.eq(SC_TESTPUB_ACTIVE, obj.getScTestpubActive()));
			}
			//补充
			
			count = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
			session.close();
			return count;
		} catch (RuntimeException re) {
			log.error("find the number of ZsSchool instance failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List findByHql(final int pageNumber ,final int pageSize, final String hql, final Object[] values){
		log.debug("finding ZsSchool instance by hql");
	    return (List<ZsSchool>) super.getHibernateTemplate().execute(new HibernateCallback(){
	        public Object doInHibernate(Session session) throws HibernateException, SQLException {
	            Query query=session.createQuery(hql);
	            if (values != null) {// 为hql语句传入参数
					for (int i = 0; i < values.length; i++) {
						query.setParameter(i, values[i]);
					}
				}
	            return query.setFirstResult((pageNumber-1)*pageSize).setMaxResults(pageSize).list();
	        }
	    });
	}

	@SuppressWarnings("unchecked")
	public int findCountByHql(final String hql, final Object[] values) {
		log.debug("finding the number of ZsSchool instance");
		try {
			return (Integer) super.getHibernateTemplate().execute(new HibernateCallback(){
		        public Object doInHibernate(Session session) throws HibernateException, SQLException {
		            Query query=session.createQuery(hql);
		            if (values != null) {// 为hql语句传入参数
						for (int i = 0; i < values.length; i++) {
							query.setParameter(i, values[i]);
						}
					}
					return ((Long)query.uniqueResult()).intValue();
		        }
		    });
		} catch (RuntimeException re) {
			log.error("find the number of ZsSchool instance failed", re);
			throw re;
		}
	}
	
	private boolean isEmpty(String value) {
		if (value==null || value.trim().length()==0) {
			return true;
		}
		return false;
	}
}